<?php

namespace app\model\v1\recovery;

use app\common\Ip2Region;
use app\model\message\service\StoreService;
use app\model\product\category\StoreProductCategory;
use app\model\product\product\StoreProduct;
use app\model\user\User;
use app\model\user\UserAddress;
use app\model\v1\recruit\RecruitCompany;
use app\model\v1\recruit\RecruitJobSeeker;
use app\model\v1\recruit\RecruitPersonageAuthentication;
use constants\ProductConstants;
use crmeb\traits\ModelTrait;

use think\Exception;
use think\exception\ValidateException;
use think\facade\Db;
use think\Model;

class RecoveryProduct extends Model
{
	use ModelTrait;


	protected $hidden = [
		//     'create_time','update_time','delete_time'
	];


	protected $updateTime = false;
	protected $createTime = false;


	const SALING_STATUS = 1;  //出售中
	const SALEING_STATUS = 3;  //议价中
	const SALED_STATUS = 4;  //已售出
	const DOWN_STATUS = 2;  //下架


	//protected $type = [
	//     'images' => 'json'
	//];
	public function user()
	{
		return $this->hasOne(User::class, 'uid', 'uid');
	}

	public function useraddress()
	{
		return $this->hasOne(UserAddress::class, 'uid', 'uid');
	}


	public function category()
	{
		return $this->hasOne(RecoveryProductCategory::class, 'id', 'category_id');
	}

	public function collect()
	{
		return $this->hasOne(RecoveryUserRelation::class, 'id', 'product_id');
	}

	public function searchCategoryIdAttr($query, $value)
	{
		$query->where('category_id', $value);
	}

	public function searchProductNameAttr($query, $value)
	{
		$query->where('product_name', 'like', '%' . $value . '%');
	}

	public function searchOnSaleAttr($query, $value)
	{
		$query->where('on_sale', $value);
	}

	public const EXPRESS_TYPE_FREE = 1;
	public const EXPRESS_TYPE_PAY = 2;
	public const EXPRESS_TYPE_PICKUP = 3;

	public const EXPRESS_TYPE_MAP = [
		self::EXPRESS_TYPE_FREE => '包邮',
		// self::EXPRESS_TYPE_PAY => '一口价',
		self::EXPRESS_TYPE_PICKUP => '自提'
	];

	public static function getExpressTypeCn($type)
	{
		return self::EXPRESS_TYPE_MAP[$type] ?? '';
	}

	public static function getProductList($param = [])
	{
		$param['page'] =  $param['page'] ?? 1;
		$param['limit'] =  $param['limit'] ?? 10;
		$order = ["a.id"=>"desc"];
		//按照创建时间排序
		if(!empty($param["order_ctime"])){
			if(!empty($param["order_ctime_sc"])){
				$order = ["a.id"=>"desc", "a.create_time"=> $param["order_ctime_sc"]];
			}else{
				//默认按照字段降序排序
				$order = ["a.id"=>"desc", "a.create_time"=>"desc"];
			}
		}

		$data["data"] = self::alias("a")
			->field ("a.*,a.id as product_id,b.cate_name,FROM_UNIXTIME(a.create_time) as create_time,reason,c.real_name,c.avatar,c.nickname,c.phone,case when a.is_sale=1 then '预售' else '在售' end as is_sale_text,
            case when a.status=0 then '待审核'
                when a.status=1 then '通过(出售中)'
                when a.status=2 then '不通过'
                when a.status=3 then '议价中'
                when a.status=4 then '已售出'
                end as status_text,
            case when a.on_sale=0 then '未上架'
                when a.on_sale=1 then '上架'
                when a.on_sale=2 then '下架'
                when a.on_sale=3 then '卖家下架'
                end as on_sale_text
            ")
			->join('recovery_product_category b','a.category_id=b.id','left')
			->join('user c','a.uid=c.uid','left')
			->where(function ($query) use ($param){
				$query->whereNull("a.delete_time");
				////$query->where("a.on_sale", 1);
//				$query->where("a.status", 1);
				if(!empty($param['time'])){    //根据创建日期搜索
					$wheretime = explode (',',$param['time']);
					$query->where('a.create_time', 'between', [strtotime($wheretime[0]),strtotime($wheretime[1])]);
				}
				if(!empty($param["word"])) $query->where("a.product_name",'like', '%'.$param["word"].'%');
				if(!empty($param["category_id"])) $query->where("a.category_id", $param["category_id"]);
				if(!empty($param["status_sale"])) $query->where("a.status", $param["status_sale"]);
				if(!empty($param['price'])){
					$whereprice = explode (',',$param['price']);
					$query->where('a.price', 'between', [strtotime($whereprice[0]),strtotime($whereprice[1])]);
				}
			})
			->order($order)
			->page($param['page'], $param['limit'])
			->select()->toArray();

		$data["count"] = self::alias("a")
			->field ("a.id as product_id,a.uid,a.category_id,a.product_name,a.product_desc,a.price,a.address,a.status,a.create_time,b.cate_name")
			->join ('recovery_product_category b','a.category_id=b.id','left')
			->where(function ($query) use ($param){
				$query->whereNull("a.delete_time");
				////$query->where("a.on_sale", 1);
				$query->where("a.status", 1);
				if(!empty($param['time'])){    //根据创建日期搜索
					$wheretime = explode (',',$param['time']);
					$query->where('a.create_time', 'between', [strtotime($wheretime[0]),strtotime($wheretime[1])]);
				}
				if(!empty($param["word"])) $query->where("a.product_name",'like', '%'.$param["word"].'%');
				if(!empty($param["category_id"])) $query->where("a.category_id", $param["category_id"]);
				if(!empty($param["status_sale"])) $query->where("a.status", $param["status_sale"]);
				if(!empty($param['price'])){
					$whereprice = explode (',',$param['price']);
					$query->where('a.price', 'between', [strtotime($whereprice[0]),strtotime($whereprice[1])]);
				}
			})
			->count();

		if(!empty($data["data"])){
			foreach ($data["data"] as $key => &$val){
				$val["pid_name"] = RecoveryProductCategory::getCatePidName($val["category_id"]);
                if($val['is_sale'] == 1){
                    if(time() >= strtotime($val["pre_sale_date"] ?? 0)){
                        $val['is_sale_text'] = '在售';
                        $val['is_sale'] = 2;
                    }else{
                        $val['is_sale_text'] = '预售';
                    }
                }else{
                    $val['is_sale_text']    = $val["is_sale"] == 1 ? '预售' : '在售';
                }
			}
		}

		$data["list_count"] = self::getListRecoveryCount();

		return $data;
	}
	public static function getProductLists($param = [])
	{
		$param['page'] =  $param['page'] ?? 1;
		$param['limit'] =  $param['limit'] ?? 10;
		$order = ["a.id"=>"desc"];
		//按照创建时间排序
		if(!empty($param["order_ctime"])){
			if(!empty($param["order_ctime_sc"])){
				$order = ["a.id"=>"desc", "a.create_time"=> $param["order_ctime_sc"]];
			}else{
				//默认按照字段降序排序
				$order = ["a.id"=>"desc", "a.create_time"=>"desc"];
			}
		}

		$data["data"] = self::alias("a")
			->field ("a.*,a.id as product_id,b.cate_name,FROM_UNIXTIME(a.create_time) as create_time,reason,c.real_name,c.avatar,c.nickname,c.phone,case when a.is_sale=1 then '预售' else '在售' end as is_sale_text,
            case when a.status=0 then '待审核'
                when a.status=1 then '通过(出售中)'
                when a.status=2 then '不通过'
                when a.status=3 then '议价中'
                when a.status=4 then '已售出'
                end as status_text,
            case when a.on_sale=0 then '未上架'
                when a.on_sale=1 then '上架'
                when a.on_sale=2 then '下架'
                when a.on_sale=3 then '卖家下架'
                end as on_sale_text
            ")
			->join('recovery_product_category b','a.category_id=b.id','left')
			->join('user c','a.uid=c.uid','left')
			->where(function ($query) use ($param){
				$query->whereNull("a.delete_time");
				$query->where("a.on_sale", 1);
				$query->where("a.status", 1);
				if(!empty($param['time'])){    //根据创建日期搜索
					$wheretime = explode (',',$param['time']);
					$query->where('a.create_time', 'between', [strtotime($wheretime[0]),strtotime($wheretime[1])]);
				}
				if(!empty($param["word"])) $query->where("a.product_name",'like', '%'.$param["word"].'%');
				if(!empty($param["category_id"])) $query->where("a.category_id", $param["category_id"]);
				if(!empty($param["status_sale"])) $query->where("a.status", $param["status_sale"]);
				if(!empty($param['price'])){
					$whereprice = explode (',',$param['price']);
					$query->where('a.price', 'between', [strtotime($whereprice[0]),strtotime($whereprice[1])]);
				}
			})
			->order($order)
			->page($param['page'], $param['limit'])
			->select()->toArray();

		$data["count"] = self::alias("a")
			->field ("a.id as product_id,a.uid,a.category_id,a.product_name,a.product_desc,a.price,a.address,a.status,a.create_time,b.cate_name")
			->join ('recovery_product_category b','a.category_id=b.id','left')
			->where(function ($query) use ($param){
				$query->whereNull("a.delete_time");
				////$query->where("a.on_sale", 1);
				$query->where("a.status", 1);
				if(!empty($param['time'])){    //根据创建日期搜索
					$wheretime = explode (',',$param['time']);
					$query->where('a.create_time', 'between', [strtotime($wheretime[0]),strtotime($wheretime[1])]);
				}
				if(!empty($param["word"])) $query->where("a.product_name",'like', '%'.$param["word"].'%');
				if(!empty($param["category_id"])) $query->where("a.category_id", $param["category_id"]);
				if(!empty($param["status_sale"])) $query->where("a.status", $param["status_sale"]);
				if(!empty($param['price'])){
					$whereprice = explode (',',$param['price']);
					$query->where('a.price', 'between', [strtotime($whereprice[0]),strtotime($whereprice[1])]);
				}
			})
			->count();

		if(!empty($data["data"])){
			foreach ($data["data"] as $key => &$val){
				$val["pid_name"] = RecoveryProductCategory::getCatePidName($val["category_id"]);
                if($val['is_sale'] == 1){
                    if(time() >= strtotime($val["pre_sale_date"] ?? 0)){
                        $val['is_sale_text'] = '在售';
                        $val['is_sale'] = 2;
                    }else{
                        $val['is_sale_text'] = '预售';
                    }
                }else{
                    $val['is_sale_text']    = $val["is_sale"] == 1 ? '预售' : '在售';
                }
			}
		}

		$data["list_count"] = self::getListRecoveryCount();

		return $data;
	}

	public static function getListRecoveryCount()
	{
		//全部  data.total
		//出售中
		$count["saling_count"] = self::where("status", self::SALING_STATUS)->count();
		//已售出
		$count["saled_count"] = self::where("status", self::SALED_STATUS)->count();
		//已下架
		$count["down_count"] = self::where("status", self::DOWN_STATUS)->count();
		return $count;
	}


	public static function getProductDetail($param = [])
	{
		$detail = self::alias("a")
			->field ("a.*,b.cate_name")
			->join ('recovery_product_category b','a.category_id=b.id','left')
			->where("a.id", $param["id"])
			->find();

		if($detail['status'] == 1){
			$detail['status_text'] = '出售中';
		}elseif($detail['status'] == 3){
			$detail['status_text'] = '议价中';
		}elseif($detail['status'] == 4){
			$detail['status_text'] = '已售出';
		}elseif($detail['status'] == 8){
			$detail['status_text'] = '下架';
		}
		$detail['create_time'] = $detail['create_time'] ? date("Y-m-d H:i:s", $detail['create_time']) : $detail['create_time'];

		return $detail;
	}


	/**
	 * 宝贝上下架
	 * @param $param
	 * @return RecoveryProduct
	 * @throws \think\db\exception\DbException
	 */
	public static function updateProductGoods($param = [])
	{
		$update = ['status' => $param["status"]];   //, 'on_sale' => $param["status"]
		if(!empty($param["reason"])) $update["reason"] = $param["reason"];
		//if($param["status"] == 1) $update["reason"] = $param["status"];

		$res = self::where("id", $param['id'])->update($update);
		return $res;
	}




	/**
	 * 首页 - 搜索 - 商品详情
	 * @param int $id
	 * @param array $param
	 * @return array
	 * @throws Exception
	 * @throws \think\db\exception\DataNotFoundException
	 * @throws \think\db\exception\ModelNotFoundException
	 * @throws \think\exception\DbException
	 */
	public static function detail(int $id, array $param = [])
	{
		$where = ['id' => $id];  //'on_sale' => 1,  , 'is_sold' => 0
		$item  = RecoveryProduct::
		with([
			"user" => function ($query) {
				$query->field("uid,nickname,real_name,phone,avatar,addres");
			},
			"useraddress" => function($query) {
				$query->where("is_default", 1)->field("uid,real_name as ship_name,phone as ship_mobile,province,city,district,detail as ship_address,longitude,latitude");
			}
		])
			->where($where)
			->find();
		if (empty($item)) throw new Exception('商品不存在');
		if ($item['on_sale'] == 2) throw new Exception('该商品已下架');
		if ($item['on_sale'] == 3) throw new Exception('商家已下架该商品');
		if (!empty($item['delete_time'])) throw new Exception('商家已删除该商品');

		$item->visit_count += 1;
		$item->save();

		$item = $item->toArray();

		$isCollect = intval(RecoveryUserRelation::where(['uid' => $param['user_id'], 'product_id' => $id])->count() > 0);
		$item['is_collect']      = $isCollect ?? 0;
		$item['express_type_cn'] = self::getExpressTypeCn($item['express_type']);
		$item['distance']        = self::getDistance($param, $item);

        if($item['is_sale'] == 1){
            if(time() >= strtotime($item["pre_sale_date"] ?? 0)){
                $item['is_sale_text'] = '在售';
                $item['is_sale'] = 2;
            }else{
                $item['is_sale_text'] = '预售';
            }
        }else{
            $item['is_sale_text']    = $item["is_sale"] == 1 ? '预售' : '在售';
        }

		$item['is_authent']      = RecoveryRegAuth::getUserIsAuth($item["uid"]);


		$item["quote_info"] = RecoveryProductQuote:: with([
			"shop" => function ($query) {
				$query->field("uid,nickname,real_name,phone,avatar");
			},
		])->where("product_id", $id)->where("uid", $param['user_id'])->order("id", "desc")
			//->where("status", 2)
			->find() ?? [];



		if (!empty($item["quote_info"])){
			if ($item["quote_info"]['status']==1||$item["quote_info"]['status']==4||$item["quote_info"]['status']==5){
				$item['detail_address']="*****";
				$item['user']['phone']=substr($item["user"]["phone"], 0, 3).'****'.substr($item["user"]["phone"], -4);
			}
		}else{
			$item['detail_address']="*****";
			$item['user']['phone']=substr($item["user"]["phone"], 0, 3).'****'.substr($item["user"]["phone"], -4);
		}

		$user_find = Db::name("user")->where("uid", $param["user_id"])->find();

		$ip2region = new Ip2Region();
		$ipInfo = $ip2region->btreeSearch($user_find["ip"] ?? '114.244.11.10');
		$item["ip_city"] = explode("|", $ipInfo["region"]??'')[2] ?? '';
		return $item;
	}



	public static function getDistance($param, $item)
	{
		if (
			(isset($param['longitude']) && $param['longitude']) &&
			(isset($item['address']['longitude']) && $item['address']['longitude'])
		) {
			return get_distance([
				$param['longitude'], $param['latitude']
			], [
				$item['address']['longitude'], $item['address']['latitude']
			]);
		}
		return 0;
	}


	/**
	 * 回收/搬家入驻
	 * @param $param
	 * @return int|string
	 * @throws Exception
	 * @throws \think\db\exception\DataNotFoundException
	 * @throws \think\db\exception\ModelNotFoundException
	 * @throws \think\exception\DbException
	 */
	public static function createRecovery($param = [])
	{
        $find = RecoveryShop::where("uid", $param["user_id"])->where("reg_type", $param["reg_type"])->find() ?? [];
        if(!empty($find)){
            $find = $find->toArray();
            $update = [
                "city_id" => $param["city_id"], //城市id
                "area_id" => $param["area_id"], //区域id
                "recovery_type" => $param["recovery_type"], //回收类型
                "type" => $param["type"], //1回收入驻  2搬家入驻
                "status" => 1,
                "update_time" => time(), //创建时间
            ];
            return Db::name("recovery_shop")->where("id", $find["id"])->update($update);
        }else{
            $add_data = [
                "uid" => $param["user_id"],  //用户id
                "reg_type" => $param["reg_type"], //注册类型
                "city_id" => $param["city_id"], //城市id
                "area_id" => $param["area_id"], //区域id
                "recovery_type" => $param["recovery_type"], //回收类型
                "type" => $param["type"], //1回收入驻  2搬家入驻
                "create_time" => time(), //创建时间
            ];
            return Db::name("recovery_shop")->insert($add_data);
        }
	}


	/**
	 * 个人实名认证提交
	 * @param $param
	 * @return int|string
	 */
	public static function addRegAuthent($param = [])
	{
		//校验是否已认证
		$find = Db::name("recovery_reg_auth")->where(["idcard"=>$param["idcard"]])->find();
		if(!empty($find)) throw new Exception("不能重复认证添加！");

		$add_data = [
			"uid" => $param["user_id"],  //创建人id
			"valid_type" => $param["valid_type"], //证件类型
			"name" => $param["name"], //姓名
			"idcard" => $param["idcard"], //身份证号
			"img" => $param["img"], //图片
			"create_time" => time(), //创建时间
		];
		return Db::name("recovery_reg_auth")->insert($add_data);
	}



	/**
	 * 店铺认证提交
	 * @param $param
	 * @return int|string
	 */
	public static function addRegAuthentShop($param = [])
	{
		$add_data = [
			"uid" => $param["user_id"],  //创建人id
			"shop_name" => $param["shop_name"], //店铺名称
			"logo" => $param["logo"], //店铺LOGO
			"img" => $param["img"], //图片
			"create_time" => time(), //创建时间
		];
		return Db::name("recovery_reg_shop")->insert($add_data);
	}



	/**
	 * 首页 - 闲置发布 - 单品发布
	 * @param $param
	 * @return bool|int
	 */
	public static function addProduct($param = [])
	{
		$reg_find = RecruitPersonageAuthentication::where(["u_id"=>$param["user_id"]])->whereNull("delete_at")->find();
		if(empty($reg_find))  throw new Exception("请先实名认证！");
		if(!empty($find["status"])){
			if($find["status"] == 1) {
				throw new Exception("审核中，请实名审核通过后再发布！");
			}else if($find["status"] == 3) {
				throw new Exception("审核未通过，请实名认证审核！");
			}
		}

        $find = self::where(function ($query) use ($param){
                $query->whereNull("delete_time");
                $query->where(["uid"=>$param["user_id"], "product_name"=>$param["product_name"]]);
                $query->whereNotIn("status", [3,4]);
                //$query->where("category_id", $param["category_id"]);
            })
            ->find();
        if(!empty($find)) throw new Exception("宝贝不能重复添加！");


		//更新店铺信息
		if(!empty($param["shop_id"])){
			if(empty($param["shop_id"])) throw new Exception("shop_id不能为空！");
			if(empty($param["shop_name"])) throw new Exception("shop_name不能为空！");
			if(empty($param["logo"])) throw new Exception("logo不能为空！");

			$update = [
				"title" => $param["shop_name"],  //店铺名称
				"logo" => $param["logo"],  //店铺名称
				"id" => $param["shop_id"],  //店铺id
			];
			RecoveryProductShop::updateProductShop($update);
		}

		//创建店铺
		if(!empty($param["shop_name"]) && !empty($param["logo"]) && !empty($param["category_id"]) && !empty($param["type"]) && empty($param["shop_id"])){
			$param["title"] = $param["shop_name"];    //店铺标题
			RecoveryProductShop::addProductShop($param);
		}

		$add = self::formatProductAdd($param);
		return Db::name("recovery_product")->insert($add);
	}




	public static function addProductCard($param = [])
	{
		$find = self::where(function ($query) use ($param){
			$query->whereNull("delete_time");
			$query->where(["uid"=>$param["user_id"], "product_name"=>$param["product_name"]]);
			$query->whereNotIn("status", [3,4]);
			//$query->where("category_id", $param["category_id"]);
		})
			->find();
		if(!empty($find))  throw new Exception("不能重复添加！");

		$reg_find = RecruitPersonageAuthentication::where(["u_id"=>$param["user_id"]])->whereNull("delete_at")->find();
		if(empty($reg_find))  throw new Exception("请先实名认证！");
		if(!empty($find["status"])){
			if($find["status"] == 1) {
				throw new Exception("审核中，请实名审核通过后再发布！");
			}else if($find["status"] == 3) {
				throw new Exception("审核未通过，请实名认证审核！");
			}
		}

		$add = self::formatProductAdd($param);
		return Db::name("recovery_product")->insert($add);
	}


	public static function formatProductAdd($param = [])
	{
		$add = [
			'uid'               => $param['user_id'],  //用户id
			'category_id'       => $param['category_id'] ?? '',  //商品分类
			'product_name'      => $param['product_name'] ?? '',  //商品名称
			'freshness_rate'    => $param['freshness_rate'] ?? '',  //新旧程度    //交易方式
			'brand'             => $param['brand'] ?? '',  //品牌   //面值
			'warranty'          => $param['warranty'] ?? '',  //是否质保 1是 2否   //卡片类型
			'product_mode'      => $param['product_mode'] ?? NULL,  //型号  //卡类面值
			'product_desc'      => $param['product_desc'] ?? NULL,  //描述
			'use_date'          => $param['use_date'] ?? '',  //使用时间
			'is_invoice'        => $param['is_invoice'] ?? '',  //是否有发票  1是 2否
			'is_sale'           => $param['is_sale'] ?? '',  //是否预售  1是 2否
			'pre_sale_date'     => $param['pre_sale_date'] ?? NULL,  //预售时间
			'is_refund'         => $param['is_refund'] ?? '',  //退货
			'is_sold'           => $param['is_sold'] ?? '',  //是否已经出售
			'visit_count'       => $param['visit_count'] ?? '',  //浏览量
			'images'            => $param['images'] ?? '',  //图片
			'content'           => $param['content'] ?? '',  //详情
			'express_type'      => $param['express_type'] ?? '',  //物流方式 ，1-包邮，2-一口价，3-自提
			'origin_price'      => $param['origin_price'] ?? '',  //原价
			'deposit_price'     => $param['deposit_price'] ?? '0.00',  //定金   剩余金额
			'price'             => $param['price'] ?? '0.00',  //价格    //卡类转让价格
			'train_time'        => $param['train_time'] ?? '',  //交易时间    //卡类转让有效期
			'address'           => $param['address'] ?? '',  //取件地址
			'detail_address'    => $param['detail_address'] ?? '',  //详细地址
			'on_sale'           => $param['on_sale'] ?? '0',  //上下架  1上架  2下架
			'status'            => $param['status'] ?? '0',
			'is_perip'          => $param['is_perip'] ?? '0',   //商品显示类型： 2周边好物
			'dx'                => $param['dx'] ?? '',   //经纬度
			'logo'              => $param['logo'] ?? '',   //logo
			'shop_name'         => $param['shop_name'] ?? '',   //商铺名称
			'type'              => $param['type'] ?? '1',   //1商品 2卡类
			'create_time'       => time(),   //创建时间
		];
		return $add;
	}



	/**
	 * 获取闲置好物 - 商品列表
	 * @param $params
	 * @return \think\Paginator
	 * @throws \think\exception\DbException
	 */
	public static function getPeripProductList($params = [])
	{
		$data["data"] = self::alias("a")
			->field("a.*, case when a.is_sale=1 then '预售' else '在售' end as is_sale_text,c.nickname,c.phone,c.avatar")
			->join('recovery_product_category b', 'a.category_id=b.id','left')
			->join('user c', 'a.uid=c.uid','left')
			->whereNull("a.delete_time")
			->where("a.on_sale", 1)
			->whereNotIn("a.status", [3,4])
			->order(['a.visit_count' => 'desc', 'a.price'=>'asc'])
			->page($params["page"], $params['limit'])
			->select()->toArray();

		$data["count"] = self::alias("a")
			->field("a.*, case when a.is_sale=1 then '预售' else '在售' end as is_sale_text,c.nickname,c.phone,c.avatar")
			->join('recovery_product_category b', 'a.category_id=b.id','left')
			->join('user c', 'a.uid=c.uid','left')
			->whereNull("a.delete_time")
			->where("a.on_sale", 1)
			->whereNotIn("a.status", [3,4])
			->count();

		if(!empty($data["data"])){
			foreach ($data['data'] as $key => &$val) {
				if(!empty($params["user_dx"])) {
					$yx = explode(',', $params["user_dx"]);
					$val['distance'] = self::get_distance(explode(",", $val["dx"]), $yx);
				}

                if($val['is_sale'] == 1){
                    if(time() >= strtotime($val["pre_sale_date"] ?? 0)){
                        $val['is_sale_text'] = '在售';
                        $val['is_sale'] = 2;
                    }else{
                        $val['is_sale_text'] = '预售';
                    }
                }else{
                    $val['is_sale_text']    = $val["is_sale"] == 1 ? '预售' : '在售';
                }

				$val["user"] = (object)[
					"uid" => $val['uid'],
					"nickname" => $val['nickname'],
					"avatar" => $val['avatar'],
				];
			}
		}

		return $data;
	}



	public static function getCardProductList($params = [])
	{
		//获取自由市场的分类的id
		$cate_id = RecoveryProductCategory::getCardCateId();
		$data["data"] = self::alias("a")
			->field("a.*, case when a.is_sale=1 then '预售' else '在售' end as is_sale_text,c.nickname,c.phone,c.avatar")
			->join('recovery_product_category b', 'a.category_id=b.id','left')
			->join('user c', 'a.uid=c.uid','left')
			->where(function ($query) use ($params, $cate_id){
				$query->whereNull("a.delete_time");
				$query->where("a.on_sale", 1);
				$query->whereNotIn("a.status", [3,4]);
				$query->where("a.category_id", $cate_id);
			})
			->order(['a.visit_count' => 'desc', 'a.price'=>'asc'])
			->page($params["page"], $params['limit'])
			->select()->toArray();

		$data["count"] = self::alias("a")
			->field("a.*, case when a.is_sale=1 then '预售' else '在售' end as is_sale_text,c.nickname,c.phone,c.avatar")
			->join('recovery_product_category b', 'a.category_id=b.id','left')
			->join('user c', 'a.uid=c.uid','left')
			->where(function ($query) use ($params, $cate_id){
				$query->whereNull("a.delete_time");
				$query->where("a.on_sale", 1);
				$query->whereNotIn("a.status", [3,4]);
				$query->where("a.category_id", $cate_id);
			})
			->count();

		if(!empty($data["data"])){
			foreach ($data['data'] as $key => &$val) {
				if(!empty($params["user_dx"])) {
					$yx = explode(',', $params["user_dx"]);
					$val['distance'] = self::get_distance(explode(",", $val["dx"]), $yx);
				}
				$val["user"] = (object)[
					"uid" => $val['uid'],
					"nickname" => $val['nickname'],
					"avatar" => $val['avatar'],
				];
			}
		}

		return $data;
	}


	/**
	 * 根据经纬度地址 获取距离
	 * @param $from  array 发件人经纬度
	 * @param $to    array  收件人经纬度
	 * @param $km    bool   true 单位千米      false 单位米
	 * @param $decimal  int 保留几位小数点
	 * @return float
	 */
	public static function get_distance($from,$to,$km=false,$decimal=2)
	{
		ini_set("error_reporting","E_ALL & ~E_NOTICE");
		sort($from);
		sort($to);

		$EARTH_RADIUS = 6370.996; // 地球半径系数

		$distance = $EARTH_RADIUS * 2 * asin(sqrt(pow(sin(($from[0] * pi() / 180 - $to[0] * pi() / 180) / 2), 2) + cos($from[0] * pi() / 180) * cos($to[0] * pi() / 180) * pow(sin(($from[1] * pi() / 180 - $to[1] * pi() / 180) / 2), 2))) * 1000;

		if ($km) {
			$distance = $distance / 1000;
		}

		return round($distance, $decimal);
	}


	/**
	 * 首页 - top区域 - 搜索
	 * @param $params
	 * @return \think\Paginator
	 * @throws \think\exception\DbException
	 */
	public static function getTopSearchList($params = [])
	{
		//获取搜索的条件where
		// 根据搜索的条件去拼接成sql查询数据库的条件
		$data["data"] = self::alias("a")
			->field("a.*,b.cate_name")
			->join('recovery_product_category b', 'a.category_id=b.id','left')
			->where(function ($query) use ($params){
				$where = self::getSearchListWhere($query, $params);
				$query->where($where);
			})
			->order(['a.id' => 'desc'])
			->page($params["page"], $params['limit'])
			->select()->toArray();

		$data["count"] = self::alias("a")
			->join('recovery_product_category b', 'a.category_id=b.id','left')
			->where(function ($query) use ($params){
				$where = self::getSearchListWhere($query, $params);
				$query->where($where);
			})
			->count();

		return $data;
	}




	/**
	 * 获取首页top搜索的where
	 * @param $params
	 * @return array
	 */
	public static function getSearchListWhere($query, $params)
	{
		$query->where("a.status", 1);
		//根据商品名称搜索
		if(!empty($params['word'])) {
			$query->where('a.product_name', 'like', "%".$params['word']."%");
			//添加一条用户搜索
			self::addUserSearchHistory([
				"user_id" => $params["user_id"],  //用户id
				"word" => $params["word"],  //搜索关键字
			]);
		}
		return $query;
	}


	/**
	 * 新增一条用户搜索
	 * @param $add
	 * @return false|int|string
	 */
	public static function addUserSearchHistory($add = [])
	{
		if(empty($add["user_id"]) || empty($add["word"])) return false;

		//添加一条用户的搜索数据
		$word_find = Db::name("recovery_user_search_history")->where("keyword", $add["word"])->find();
		if(empty($word_find)){
			$add_data = [
				'uid' => $add['user_id'],
				'keyword' => $add['word'],
				'create_time' => time(),
			];
			$res = Db::name("recovery_user_search_history")->insert($add_data);
		}else{
			Db::name("recovery_user_search_history")->where("id", $word_find["id"])->update(["update_time"=>time()]);
			$res = 1;
		}
		return $res;
	}


	/**
	 * 我发布的 - 全部商品
	 * @param $params
	 * @return \think\Paginator
	 * @throws \think\exception\DbException
	 */
	public static function getMyPublishList($params = [])
	{
		//接收用户发送过来的参数，传到where条件当中，从数据库检索数据
		$data["data"] = self::alias("a")
			->field("a.*,b.cate_name,c.nickname,c.avatar,c.phone,
              case when a.status=0 then '待审核' 
                    when a.status=1 then '通过' 
                    when a.status=2 then '不通过' 
                    when a.status=3 then '交易中' 
                    when a.status=4 then '买家已确认收货' 
                    end as status_text,
              case when a.on_sale=0 then '待上架' 
                    when a.on_sale=1 then '上架' 
                    when a.on_sale=2 then '下架' 
                    when a.on_sale=3 then '商家下架' 
                    end as on_sale_text
            ")
			->join('recovery_product_category b', 'a.category_id=b.id','left')
			->join('user c', 'a.uid=c.uid','left')
			->where(function ($query) use ($params){
				$query->whereNull("a.delete_time");
				$query->where("a.uid", $params["user_id"]);
//				$query->where("a.status", '<=', 3);
				//获取已下架的2
				if(!empty($params["on_sale"])){    ////$params["on_sale"]
					if($params["on_sale"] == 2){
						$query->whereIn("a.on_sale", [2,3]);
						$query->where("a.status", "<>", 0);
					}
					if($params["on_sale"] == 1) $query->whereIn("a.on_sale", [1]);
				}
				//获取在售卖的1
				if(!empty($params["is_sale"])){
					$query->where("a.is_sale", $params["is_sale"]);
					$query->where("a.on_sale", 1);
				}
				//获取审核
				if(!empty($params["audit"])){
					$query->whereIn("a.status", [0, 2]);
				}
			})
			->order(['a.id' => 'desc'])
			->page($params["page"], $params['limit'])
			->select()->toArray();

		$data["count"] = self::alias("a")
			->field("a.*,b.cate_name,c.nickname,c.avatar,c.phone")
			->join('recovery_product_category b', 'a.category_id=b.id','left')
			->join('user c', 'a.uid=c.uid','left')
			->where(function ($query) use ($params){
				$query->whereNull("a.delete_time");
				$query->where("a.uid", $params["user_id"]);
//				$query->where("a.status", '<=', 2);
				//获取已下架的2
				if(!empty($params["on_sale"])){    ////$params["on_sale"]
					if($params["on_sale"] == 2){
						$query->whereIn("a.on_sale", [2,3]);
						$query->where("a.status", "<>", 0);
					}
					if($params["on_sale"] == 1) $query->whereIn("a.on_sale", [1]);
				}
				//获取在售卖的1
				if(!empty($params["is_sale"])){
					$query->where("a.is_sale", $params["is_sale"]);
					$query->where("a.on_sale", 1);
				}
				//获取审核中
				if(!empty($params["audit"])){
					$query->whereIn("a.status", 0);  //[0, 2]
				}
			})
			->count();

		$data["shop_data"] = RecoveryProductShop::alias("a")
			->field("a.*,b.cate_name,c.nickname,c.avatar,c.phone,
            case when a.status=1 then '待审核' 
                    when a.status=2 then '通过' 
                    when a.status=3 then '不通过' 
                    end as status_text,
              case when a.on_sale=0 then '待上架' 
                    when a.on_sale=1 then '上架' 
                    when a.on_sale=2 then '下架' 
                    end as on_sale_text
            ")
			->join('recovery_product_category b', 'a.category_id=b.id','left')
			->join('user c', 'a.uid=c.uid','left')
			->where(function ($query) use ($params){
				$query->whereNull("a.delete_time");
				$query->where("a.uid", $params["user_id"]);
				$query->where("a.is_shop", 1);
				//获取已下架的2
				if(!empty($params["on_sale"])){
					if($params["on_sale"] == 2){
						$query->whereIn("a.on_sale", [2,3]);
						$query->where("a.status", "<>", 0);
					}
					if($params["on_sale"] == 1) $query->whereIn("a.on_sale", [1]);
				}
				//审核中
				if(!empty($params["audit"])){
					$query->whereIn("a.status", $params["audit"]); //[1, 3]
				}
				//在售
				if(!empty($params["sale_text"])){
					$query->where("a.status", 2);
				}
			})
			->order(['a.id' => 'desc'])
			->page($params["page"], $params['limit'])
			->select()->toArray();

		if(!empty($data["data"])){
			foreach ($data['data'] as $key => &$val) {
				$val["user"] = (object)[
					"uid" => $val['uid'],
					"nickname" => $val['nickname'],
					"avatar" => $val['avatar'],
				];
			}
		}


		return $data;
	}



	/**
	 * 我发布的 - count
	 * @param $params
	 * @return int|string
	 * @throws Exception
	 */
	public static function getMyPublishListCount($params = [])
	{
		//接收用户发送的参数，根据用户的uid获取用户发布的全部商品
		$product_count = self::alias("a")
			->join('recovery_product_category b', 'a.category_id=b.id','left')
			->where(function ($query) use ($params){
				$query->where("a.delete_time",null);
				$query->where("a.uid", $params["user_id"]);
//				$query->where("a.status", '<=', 2);
			})
			->count() ?? 0;

		$product_shop_count = RecoveryProductShop::
		where(function ($query) use ($params){
			$query->where("delete_time",null);
			$query->where("uid", $params["user_id"]);
			$query->where("is_shop", 1);
		})
			->count() ?? 0;

		return $product_count + $product_shop_count;
	}



	/**
	 * 我的发布 - 商品编辑
	 * @param $param
	 * @return bool|int
	 */
	public static function updateProduct($param = [])
	{
		$update = self::formatProductUpdate($param);

		if(!empty($param["on_sale"]) && ($param["on_sale"] === 111)){
			$update["on_sale"] = 0;
			$update["status"] = 0;
		}

		return Db::name("recovery_product")->where("id", $param["id"])->update($update);
	}


	public static function formatProductUpdate($param = [])
	{
		$update["update_time"] = time();   //更新时间
		if(!empty($param['user_id']))           $update["uid"] = $param['user_id']; //用户id
		if(!empty($param['category_id']))       $update["category_id"] = $param['category_id']; //商品分类
		if(!empty($param['product_name']))      $update["product_name"] = $param['product_name']; //商品名称
		if(!empty($param['freshness_rate']))    $update["freshness_rate"] = $param['freshness_rate']; //新旧程度
		if(!empty($param['brand']))             $update["brand"] = $param['brand']; //品牌
		if(!empty($param['warranty']))          $update["warranty"] = $param['warranty']; //是否质保 1是 2否
		if(!empty($param['product_mode']))      $update["product_mode"] = $param['product_mode']; //型号
		if(!empty($param['product_desc']))      $update["product_desc"] = $param['product_desc']; //描述
		if(!empty($param['use_date']))          $update["use_date"] = $param['use_date']; //使用时间
		if(!empty($param['is_invoice']))        $update["is_invoice"] = $param['is_invoice']; //是否有发票  1是 2否
		if(!empty($param['is_sale']))           $update["is_sale"] = $param['is_sale']; //是否预售  1是 2否
		if(!empty($param['pre_sale_date']))     $update["pre_sale_date"] = $param['pre_sale_date']; //预售时间
		if(!empty($param['is_refund']))         $update["is_refund"] = $param['is_refund']; //退货
		if(!empty($param['is_sold']))           $update["is_sold"] = $param['is_sold']; //是否已经出售
		if(!empty($param['visit_count']))       $update["visit_count"] = $param['visit_count']; //是否已经出售
		if(!empty($param['images']))            $update["images"] = $param['images']; //图片
		if(!empty($param['content']))           $update["content"] = $param['content']; //详情
		if(!empty($param['express_type']))      $update["express_type"] = $param['express_type']; //物流方式 ，1-包邮，2-一口价，3-自提
		if(!empty($param['origin_price']))      $update["origin_price"] = $param['origin_price']; //原价
		if(!empty($param['deposit_price']))     $update["deposit_price"] = $param['deposit_price'] ?? '0.00'; //定金
		if(!empty($param['price']))             $update["price"] = $param['price']; //价格
		if(!empty($param['address']))           $update["address"] = $param['address']; //卖家地址
		if(!empty($param['on_sale']))           $update["on_sale"] = $param['on_sale']; //上下架  1上架  2下架
		if(!empty($param['status']))            $update["status"] = $param['status']; //
		if(!empty($param['is_perip']))          $update["is_perip"] = $param['is_perip']; //商品显示类型： 2周边好物
		if(!empty($param['train_time']))        $update["train_time"] = $param['train_time']; //
		if(!empty($param['dx']))                $update["dx"] = $param['dx']; //经纬度
		if(!empty($param['log']))               $update["log"] = $param['log']; //log
		if(!empty($param['shop_name']))         $update["shop_name"] = $param['shop_name']; //店铺名称
		if(!empty($param['logo']))              $update["logo"] = $param['logo']; //店铺名称
		if(!empty($param['reset']))             $update["status"] = 0;

		return $update;
	}



	/**
	 * 我的发布 - 商品编辑
	 * @param $param
	 * @return bool|int
	 */
	public static function updatePublishCard($param = [])
	{
		$update = self::formatProductCardUpdate($param);
		return Db::name("recovery_product")->where("id", $param["id"])->update($update);
	}


	public static function formatProductCardUpdate($param = [])
	{
		$update["update_time"] = time();   //更新时间
		if(!empty($param['user_id']))           $update["uid"] = $param['user_id']; //用户id
		if(!empty($param['category_id']))       $update["category_id"] = $param['category_id']; //商品分类
		if(!empty($param['product_name']))      $update["product_name"] = $param['product_name']; //商品名称
		if(!empty($param['freshness_rate']))    $update["freshness_rate"] = $param['freshness_rate']; //新旧程度
		if(!empty($param['brand']))             $update["brand"] = $param['brand']; //品牌
		if(!empty($param['warranty']))          $update["warranty"] = $param['warranty']; //是否质保 1是 2否
		if(!empty($param['product_mode']))      $update["product_mode"] = $param['product_mode']; //型号  //卡类面值
		if(!empty($param['product_desc']))      $update["product_desc"] = $param['product_desc']; //描述
		if(!empty($param['use_date']))          $update["use_date"] = $param['use_date']; //使用时间
		if(!empty($param['is_invoice']))        $update["is_invoice"] = $param['is_invoice']; //是否有发票  1是 2否
		if(!empty($param['is_sale']))           $update["is_sale"] = $param['is_sale']; //是否预售  1是 2否
		if(!empty($param['pre_sale_date']))     $update["pre_sale_date"] = $param['pre_sale_date']; //预售时间
		if(!empty($param['is_refund']))         $update["is_refund"] = $param['is_refund']; //退货
		if(!empty($param['is_sold']))           $update["is_sold"] = $param['is_sold']; //是否已经出售
		if(!empty($param['visit_count']))       $update["visit_count"] = $param['visit_count']; //是否已经出售
		if(!empty($param['images']))            $update["images"] = $param['images']; //图片
		if(!empty($param['content']))           $update["content"] = $param['content']; //详情
		if(!empty($param['express_type']))      $update["express_type"] = $param['express_type']; //物流方式 ，1-包邮，2-一口价，3-自提
		if(!empty($param['origin_price']))      $update["origin_price"] = $param['origin_price']; //原价
		if(!empty($param['deposit_price']))     $update["deposit_price"] = $param['deposit_price'] ?? '0.00'; //定金
		if(!empty($param['price']))             $update["price"] = $param['price']; //价格    //卡类转让价格
		if(!empty($param['address']))           $update["address"] = $param['address']; //卖家地址
		if(!empty($param['on_sale']))           $update["on_sale"] = $param['on_sale']; //上下架  1上架  2下架
		if(!empty($param['is_perip']))          $update["is_perip"] = $param['is_perip']; //商品显示类型： 2周边好物
		if(!empty($param['train_time']))        $update["train_time"] = $param['train_time']; //
		if(!empty($param['dx']))                $update["dx"] = $param['dx']; //经纬度
		if(!empty($param['log']))               $update["log"] = $param['log']; //log
		if(!empty($param['shop_name']))         $update["shop_name"] = $param['shop_name']; //店铺名称
		if(!empty($param['logo']))              $update["logo"] = $param['logo']; //店铺名称
		if(!empty($param['status']))            $update["status"] = $param['status'];
		if(!empty($param['reset']))             $update["status"] = 0;

		return $update;
	}






	/**
	 * 我的发布 -   2下架     111申请上架
	 * @param $param
	 * @return int|string
	 * @throws Exception
	 * @throws \think\db\exception\DbException
	 * @throws \think\exception\PDOException
	 */
	public static function enablePublish($param = [])
	{
		//111 是上架
		if($param["on_sale"] === 111){
			$update["on_sale"] = 1;
			$update["status"] =  0;
		}
		//2 是上架   商家 下架
		if($param["on_sale"] === 2){
			$update["on_sale"] = 3;
		}

		$find = RecoveryProductQuote::where("product_id", $param["id"])->whereIn("status", [2,3])->find();
		if(!empty($find)) Throw new Exception('此商品正在交易当中！');

		return Db::name("recovery_product")->where("id", $param["id"])->update($update);
	}


	/**
	 * 获取商品列表
	 * @param $params
	 * @return \think\Paginator
	 * @throws \think\exception\DbException
	 */
	public static function getCateProductList($params = [])
	{
		$data["data"] = self::alias("a")
			->field("a.*,c.nickname,c.real_name,c.phone,c.avatar")
			->join('recovery_product_category b', 'a.category_id=b.id','left')
			->join('user c', 'a.uid=c.uid','left')
			->where(function ($query) use ($params){
				$query->whereNull("a.delete_time");
				$query->where("a.on_sale", 1);
				$query->whereNotIn("a.status", [3, 4]);
				$query->where("a.category_id", $params["category_id"]);
				//根据店铺(商品)名称搜索
				if(!empty($params["product_name"])) $query->where("a.product_name", 'like', '%'.$params["product_name"].'%');
			})
			->order(['a.id' => 'desc'])
			->page($params["page"], $params['limit'])
			->select()->toArray();

		$data["count"] = self::alias("a")
			->field("a.*,c.nickname,c.real_name,c.phone,c.avatar")
			->join('recovery_product_category b', 'a.category_id=b.id','left')
			->join('user c', 'a.uid=c.uid','left')
			->where(function ($query) use ($params){
				$query->whereNull("a.delete_time");
				$query->where("a.on_sale", 1);
				$query->whereNotIn("a.status", [3, 4]);
				$query->where("a.category_id", $params["category_id"]);
				//根据店铺(商品)名称搜索
				if(!empty($params["product_name"])) $query->where("a.product_name", 'like', '%'.$params["product_name"].'%');
			})
			->count();

		return $data;
	}



	/**
	 * 我的发布 - 商品删除
	 * @param $param
	 * @return int|string
	 * @throws Exception
	 * @throws \think\db\exception\DbException
	 * @throws \think\exception\PDOException
	 */
	public static function delPublish($param = [])
	{
		return Db::name("recovery_product")->where("id", $param["id"])->update(["delete_time"=>time()]);
	}


	/**
	 * 获取回收/搬家入驻列表
	 * @param $params
	 * @return \think\Paginator
	 * @throws \think\db\exception\DbException
	 * @throws \think\exception\DbException
	 */
	public static function getRecoveryShopList($params = [])
	{
		$data["data"] = Db::name("recovery_shop")
			->alias("a")
			->field("FROM_UNIXTIME(a.create_time) as ctime,a.id,a.uid,a.reg_type,a.city_id,a.area_id,a.recovery_type,a.create_time,a.type,
            b.nickname,b.real_name,b.phone,b.avatar")
			->join('user b', 'a.uid=b.uid','left')
			->where(function ($query) use ($params){
				$query->where("a.status", 2);
				//1回收入驻  2搬家入驻
				if(!empty($params["type"])) $query->where("a.type", $params["type"]);
			})
			->order(['a.id' => 'desc'])
			->page($params["page"], $params['limit'])
			->select()->toArray();

		$data["count"] = Db::name("recovery_shop")
			->alias("a")
			->field("FROM_UNIXTIME(a.create_time) as ctime,a.id,a.uid,a.reg_type,a.city_id,a.area_id,a.recovery_type,a.create_time,a.type,
            b.nickname,b.real_name,b.phone,b.avatar")
			->join('user b', 'a.uid=b.uid','left')
			->where(function ($query) use ($params){
				$query->where("a.status", 2);
				//1回收入驻  2搬家入驻
				if(!empty($params["type"])) $query->where("a.type", $params["type"]);
			})
			->count();

        if(!empty($data["data"])){
            foreach ($data["data"] as $key => &$val){
                if($val["type"] == 1){
                    $val["sys_text"] = RecoveryQuestionCate::where("type", 24)->value("cate_name") ?? '';
                }else{
                    $val["sys_text"] = "";
                }
            }
        }


		return $data;
	}


	/**
	 * 首页 - 获取分类店铺列表
	 * @param $params
	 * @return \think\Paginator
	 * @throws \think\exception\DbException
	 */
	public static function getCateShopList($params = [])
	{
		$data = self::alias("a")
			->join('recovery_product_category b', 'a.category_id=b.id','left')
			->where(function ($query) use ($params){
				$query->where(["a.status"=> 1, "a.sort_tag"=>1]);  //1店铺  2商品
				//根据店铺(商品)名称搜索
				if(!empty($params["product_name"])) $query->where("a.product_name", 'like', '%'.$params["product_name"].'%');
			})
			->order(['a.id' => 'desc'])
			->paginate($params['limit']);

		return $data;
	}


	/**
	 * 首页 - 自由市场商品列表
	 * @param $params
	 * @return \think\Paginator
	 * @throws \think\exception\DbException
	 */
	public static function getFreeMarkList($params = [])
	{
		//获取自由市场的分类的id
		$cate_id = RecoveryProductCategory::getFreeMarkCateId();
		$data["data"] = self::alias("a")
			->field("a.*, a.id as free_id, case when a.is_sale=1 then '预售' else '在售' end as is_sale_text,c.avatar,c.nickname,c.phone")
			->join('user c', 'a.uid=c.uid','left')
			->where(function ($query) use ($params, $cate_id){
				$query->whereNull("a.delete_time");
				$query->where("a.on_sale", 1);
				$query->whereNotIn("a.status", [3,4]);
				$query->where("a.category_id", $cate_id);
			})
			->order(['a.id' => 'desc'])
			->page($params["page"], $params['limit'])
			->select()->toArray();

		$data["count"] = self::alias("a")
			->field("a.*, a.id as free_id, case when a.is_sale=1 then '预售' else '在售' end as is_sale_text,c.avatar,c.nickname,c.phone")
			->join('user c', 'a.uid=c.uid','left')
			->where(function ($query) use ($params, $cate_id){
				$query->whereNull("a.delete_time");
				$query->where("a.on_sale", 1);
				$query->whereNotIn("a.status", [3,4]);
				$query->where("a.category_id", $cate_id);
			})
			->count();

		if(!empty($data["data"])){
			foreach ($data['data'] as $key => &$val) {
				if(!empty($params["user_dx"])) {
					$yx = explode(',', $params["user_dx"]);
					$val['distance'] = self::get_distance(explode(",", $val["dx"]), $yx);
				}

                if($val['is_sale'] == 1){
                    if(time() >= strtotime($val["pre_sale_date"] ?? 0)){
                        $val['is_sale_text'] = '在售';
                        $val['is_sale'] = 2;
                    }else{
                        $val['is_sale_text'] = '预售';
                    }
                }else{
                    $val['is_sale_text']    = $val["is_sale"] == 1 ? '预售' : '在售';
                }

				$val["user"] = (object)[
					"uid" => $val['uid'],
					"nickname" => $val['nickname'],
					"avatar" => $val['avatar'],
				];
			}
		}

		return $data;
	}


	public static function getFreeIdleList($params = [])
	{
		$cate_id = RecoveryProductCategory::getFreeIdleCateId();
		$data["data"] = self::alias("a")
			->field("a.*, a.id as free_id, case when a.is_sale=1 then '预售' else '在售' end as is_sale_text,c.avatar,c.nickname,c.phone")
			->join('user c', 'a.uid=c.uid','left')
			->where(function ($query) use ($params, $cate_id){
				$query->whereNull("a.delete_time");
				$query->where("a.on_sale", 1);
				$query->where("a.category_id", $cate_id);
			})
			->order(['a.id' => 'desc'])
			->page($params["page"], $params['limit'])
			->select()->toArray();

		$data["count"] = self::alias("a")
			->field("a.*, a.id as free_id, case when a.is_sale=1 then '预售' else '在售' end as is_sale_text,c.avatar,c.nickname,c.phone")
			->join('user c', 'a.uid=c.uid','left')
			->where(function ($query) use ($params, $cate_id){
				$query->whereNull("a.delete_time");
				$query->where("a.on_sale", 1);
				$query->where("a.category_id", $cate_id);
			})
			->count();

		if(!empty($data["data"])){
			foreach ($data['data'] as $key => &$val) {
				if(!empty($params["user_dx"])) {
					$yx = explode(',', $params["user_dx"]);
					$val['distance'] = self::get_distance(explode(",", $val["dx"]), $yx);
				}
				$val["user"] = (object)[
					"uid" => $val['uid'],
					"nickname" => $val['nickname'],
					"avatar" => $val['avatar'],
				];
			}
		}

		return $data;
	}



	/**
	 * 个人中心 - 获取数量
	 * @param $params
	 * @return int[]|string[]
	 * @throws Exception
	 */
	public static function getListCount($params = [])
	{
		return [
			"publish_count" => self::getMyPublishListCount($params),  //我发布的
			"sale_count" => self::getMySaleListCount($params),  //我卖出的
			"buy_count" => self::getBuyListCount($params),  //我买到的
			"collect_count" => RecoveryUserRelation::getCollectListCount($params),  //我收藏的
		];
	}


	/**
	 * 我卖出的 - 全部商品列表
	 * @param $params
	 * @return \think\Paginator
	 * @throws \think\exception\DbException
	 */
	public static function getMySaleList($params = [])
	{
		// 接收用户传参过来的参数进行获取数据
		// 获取列表的数据中将status字段进行文本显示
		$data["data"] = self::alias("a")
			->field("b.id as quote_id,b.product_id,b.uid as buyer_id,b.quote_price,b.status,b.uid,
            a.product_name,a.price,a.images,a.dx,a.on_sale,
            c.nickname,c.phone,c.avatar,
            case when b.status=1 then '买家已出价' 
            when b.status=2 then '等待买家取货' 
            when b.status=3 then '已完成' 
            when b.status=4 then '已取消' 
            when b.status=5 then '报价失败' 
            when b.status=6 then '已拒绝' 
            end as status_text
            ")
			->join('recovery_product_quote b', 'a.id=b.product_id','left')
			->join('user c', 'b.uid=c.uid','left')
			->where(function ($query) use ($params){
				$query->whereNull("a.delete_time");
				$query->whereNull("b.delete_time");
				$query->where("b.shop_id", $params["user_id"]);  //我卖出的
				//根据状态搜索 1出价中 2待取货 3已完成 4已取消
				if(!empty($params["status"])) $query->where("b.status", $params["status"]);
			})
			->order(['b.status' => 'asc', 'b.create_time'=>'desc'])
			->page($params["page"], $params['limit'])
			->select()->toArray();

		$data["count"] = self::alias("a")
			->join('recovery_product_quote b', 'a.id=b.product_id','left')
			->join('user c', 'b.uid=c.uid','left')
			->where(function ($query) use ($params){
				$query->whereNull("a.delete_time");
				$query->whereNull("b.delete_time");
				$query->where("b.shop_id", $params["user_id"]);  //我卖出的
				//根据状态搜索 1出价中 2待取货 3已完成 4已取消
				if(!empty($params["status"])){
					$query->where("b.status", $params["status"]);
				} else{
					//$query->whereIn("b.status", [3, 4]);
				}
			})
			->count();


		$data["custer"] = StoreService::getCusterId(1);

		return $data;
	}


	/**
	 * 我卖出的 - count
	 * @param $params
	 * @return int|string
	 * @throws Exception
	 */
	public static function getMySaleListCount($params = [])
	{

		//根据用户传参的参数获取列表返回的数量count
		return self::alias("a")
			->join('recovery_product_quote b', 'a.id=b.product_id','left')
			->where(function ($query) use ($params){
				$query->whereNull("a.delete_time");
				$query->whereNull("b.delete_time");
				$query->whereIn("b.status", [1, 2, 3]);
				$query->where("b.shop_id", $params["user_id"]);  //我卖出的
			})
			->count();
	}


	/**
	 * 我卖出的 - 待取货详情
	 * @param $params
	 * @return array|bool|\PDOStatement|string|Model|null
	 * @throws \think\db\exception\DataNotFoundException
	 * @throws \think\db\exception\ModelNotFoundException
	 * @throws \think\exception\DbException
	 */
	public static function getMySaleDetail($params = [])
	{
		//根据用户id获取待取货详情的数据
		$data = self::alias("a")
			->field("b.id,b.uid,b.product_id,FROM_UNIXTIME(b.create_time) as ctime,a.product_name,a.price,a.images,c.uid as user_id,c.nickname,c.phone,
            d.detail as address,d.real_name as ship_name,d.phone as ship_mobile")
			->join('recovery_product_quote b', 'a.id=b.product_id','left')
			->join('user c', 'b.uid=c.uid','left')
			->join('user_address d', 'b.uid=d.uid','left')
			->where("b.id", $params["quote_id"])
			->find();

		return $data;
	}



	/**
	 * 我买到的 - 待取货详情
	 * @param $params
	 * @return array|bool|\PDOStatement|string|Model|null
	 * @throws \think\db\exception\DataNotFoundException
	 * @throws \think\db\exception\ModelNotFoundException
	 * @throws \think\exception\DbException
	 */
	public static function getBuyDetail($params = [])
	{
		//根据用户发送过来的参数，获取数据库中的待取货详情数据
		$detail = self::alias("a")
			->field("b.id,b.uid,b.product_id,FROM_UNIXTIME(b.create_time) as ctime,a.product_name,a.price,a.images,c.uid as user_id,c.nickname,c.phone,
            d.detail as address,d.real_name as ship_name,d.phone as ship_mobile")
			->join('recovery_product_quote b', 'a.id=b.product_id','left')
			->join('user c', 'b.shop_id=c.uid','left')
			->join('user_address d', 'b.shop_id=d.uid','left')
			->where("b.id", $params["quote_id"])
			->find();

		return $detail;
	}




	/**
	 * 我买到的 - 全部商品列表(报价列表)
	 * @param $params
	 * @return \think\Paginator
	 * @throws \think\exception\DbException
	 */
	public static function getBuyList($params = [])
	{
		$data["data"] = self::alias("a")
			->field("b.id as quote_id,b.product_id,b.quote_price,b.status,b.uid,a.on_sale,a.product_name,a.price,a.images,c.nickname,c.phone,c.avatar,
            case when b.status=1 then '出价中' 
                when b.status=2 then '待取货' 
                when b.status=3 then '已完成' 
                when b.status=4 then '已取消'
                when b.status=5 then '报价失败'
                when b.status=6 then '商家拒绝报价'
                end as quote_status_text,
            case when a.on_sale=1 then '上架' 
                when a.on_sale=2 then '下架' 
                when a.on_sale=3 then '商家下架' 
                end as on_sale_text
            ")
			->join('recovery_product_quote b', 'a.id=b.product_id','left')
			->join('user c', 'b.shop_id=c.uid','left')
			->where(function ($query) use ($params){
				$query->whereNull("a.delete_time");
				$query->whereNull("b.buy_delete_time");
				$query->where("b.uid", $params["user_id"]);
				//根据状态搜索   2待取货 3已完成 4已取消
				if(!empty($params["is_all"]))  $query->where("b.status", $params["is_all"]);
			})
			->order(['b.status' => 'asc', 'b.create_time'=>'desc'])
			->page($params["page"], $params['limit'])
			->select()->toArray();

		$data["count"] = self::alias("a")
			->field("b.id as quote_id,b.product_id,b.quote_price,b.status,b.uid,a.product_name,a.price,a.images,c.nickname,c.phone,c.avatar")
			->join('recovery_product_quote b', 'a.id=b.product_id','left')
			->join('user c', 'b.shop_id=c.uid','left')
			->where(function ($query) use ($params){
				$query->whereNull("a.delete_time");
				$query->whereNull("b.buy_delete_time");
				$query->where("b.uid", $params["user_id"]);
				//根据状态搜索   2待取货 3已完成 4已取消
				if(!empty($params["is_all"]))  $query->where("b.status", $params["is_all"]);
			})
			->count();

		if(!empty($data["data"])){
			foreach ($data['data'] as $key => &$val) {
				$val["user"] = (object)[
					"uid" => $val['uid'],
					"nickname" => $val['nickname'],
					"avatar" => $val['avatar'],
				];
			}
		}

		return $data;
	}


	/**
	 * 我买到的 - count
	 * @param $params
	 * @return int|string
	 * @throws Exception
	 */
	public static function getBuyListCount($params = [])
	{
		//根据用户发送过来的参数，获取用户买到的商品数据
		return self::alias("a")
			->join('recovery_product_quote b', 'a.id=b.product_id','left')
			->where(function ($query) use ($params){
                $query->whereNull("a.delete_time");
                $query->whereNull("b.buy_delete_time");
                $query->where("b.uid", $params["user_id"]);
			})
			->count();
	}


	/**
	 * 个人中心 - 获取个人实名认证详情
	 * @param $param
	 * @return array|bool|mixed|\PDOStatement|string|Model|null
	 * @throws \think\db\exception\DataNotFoundException
	 * @throws \think\db\exception\DbException
	 * @throws \think\db\exception\ModelNotFoundException
	 * @throws \think\exception\DbException
	 */
	public static function getRegAuthentDetail($param = [])
	{
		$where = ['uid' => $param['user_id']];
		$item  = Db::name("recovery_reg_auth")->where($where)->find() ?? [];
		return $item;
	}


	/**
	 * 新增回收/搬家入驻类型
	 * @param $param
	 * @return int|string
	 */
	public static function createRecoveryShopType($param = [])
	{
		$add_data = [
			"uid" => $param["user_id"],  //用户id
			"cate_name" => $param["recovery_type"], //回收类型
			"type" => $param["type"], //4回收入驻自定义  5搬家入驻自定义
			"create_time" => time(), //创建时间
		];
		return Db::name("recovery_question_cate")->insert($add_data);
	}


	/**
	 * 首页 - 获取轮播图
	 * @param $param
	 * @return array
	 * @throws \think\db\exception\DataNotFoundException
	 * @throws \think\db\exception\DbException
	 * @throws \think\db\exception\ModelNotFoundException
	 * @throws \think\exception\DbException
	 */
	public static function getConfigImage($param = [])
	{
		$where = ['status' => 1, 'show_position'=>$param["show_position"], 'client_type'=>$param['client_type'], 'show_type'=>1];
        if(!empty($param["cate_id"])) $where["cate_id"] = $param["cate_id"];
		$data  = Db::name("config_banner")
			->where($where)
			->order("sort", "desc")
			->select()
			->toArray();
		return $data;
	}



    public static function getConfigPageImg($param = [])
    {
        $where = ['status' => 1, 'show_position'=>42, 'show_type'=>1];
        if(!empty($param["client_type"])) $where["client_type"] = $param["client_type"];
        $data = Db::name("config_banner")
            ->where($where)
            ->order("sort", "desc")
            ->select()
            ->toArray();
        return $data;
    }


	/**
	 * 用户店铺认证信息
	 * @param $param
	 * @return array|bool|mixed|\PDOStatement|string|Model|null
	 * @throws \think\db\exception\DataNotFoundException
	 * @throws \think\db\exception\DbException
	 * @throws \think\db\exception\ModelNotFoundException
	 * @throws \think\exception\DbException
	 */
	public static function getUserShop($param = [])
	{
		return Db::name("recovery_product_shop")
			->where(["uid"=>$param["user_id"]])
			->where(function ($query) use ($param){
				if(!empty($param["category_id"])){
					$query->where("category_id", $param["category_id"])->where("status", 2);
				}
			})
			->select()->toArray() ?? [];
	}



	public static function getUserShopNot($param = [])
	{
		return Db::name("recovery_product_shop")
			->where(["uid"=>$param["user_id"]])
			->where(function ($query) use ($param){
				if(!empty($param["category_id"])){
					$query->where("category_id", $param["category_id"])->where("status", 3);
				}
			})
			->select()->toArray() ?? [];
	}




	public static function getUserShopInfo($param = [])
	{
		return Db::name("recovery_product")
			->where(["uid"=>$param["user_id"]])
			->whereNotNull("shop_name")
			->whereNotNull("logo")
			->order("id","desc")
			->limit(1)
			->find();
	}


	/**
	 * 商铺主页 - 获取商品
	 * @param $category_id
	 * @param $uid
	 * @return array
	 * @throws \think\db\exception\DataNotFoundException
	 * @throws \think\db\exception\ModelNotFoundException
	 * @throws \think\exception\DbException
	 */
	public static function getProductByCateAndUid($category_id='', $uid='')
	{
		//if(empty($category_id) || empty($uid)) return [];
		if(empty($uid)) return [];
		$product = self::field("*,
                origin_price,delete_time,express_type,
                case when is_sale=1 then '预售' 
                when is_sale=2 then '在售' 
                end as is_sale_text
                ")
			->where(function ($query) use ($category_id, $uid){
				$query->where("uid", $uid);
				$query->where("on_sale", 1);
				$query->whereNull("delete_time");
				if(!empty($category_id)) {
					if (is_array($category_id)) {
						$query->whereIn("category_id", $category_id);
					} else {
						$query->where("category_id", $category_id);
					}
				}
			})
			->select()->toArray();
		return $product;
	}




	public static function getProductByUid($uid='')
	{
		if(empty($uid)) return [];
		$product = self::field("*,
                origin_price,express_type,
                case when is_sale=1 then '预售' 
                when is_sale=2 then '在售' 
                end as is_sale_text
                ")
			->where(function ($query) use ($uid){
				$query->where("uid", $uid);
				$query->where("on_sale", 1);
				$query->whereNull("delete_time");
			})
			->select()->toArray();
		return $product;
	}



	/**
	 * 个人商家主页详情
	 * @param $param
	 * @return array|bool|mixed|\PDOStatement|string|Model
	 * @throws \think\db\exception\DataNotFoundException
	 * @throws \think\db\exception\DbException
	 * @throws \think\db\exception\ModelNotFoundException
	 * @throws \think\exception\DbException
	 */
	public static function getUserShopDetail($param = [])
	{
		$user_find = Db::name("user")->where("uid", $param["user_id"])->find();

		$user_find["tag_name"] = self::getUserShopTag($param["user_id"]);
		$ip2region = new Ip2Region();
		$ipInfo = $ip2region->btreeSearch($user_find["ip"] ?? '114.244.11.10');
		$user_find["ip_city"] = explode("|", $ipInfo["region"]??'')[2] ?? '';

		if(empty($param["category_id"])){
			$user_find["category_name"] = "";
		}else{
			$user_find["category_name"] = RecoveryProductCategory::where("id", $param["category_id"])->value("cate_name") ?? "";
		}

		//店铺下的自由市场的商品  以及办公闲置
		$free_cate_id = RecoveryProductCategory::getCategoryIdByName("自由市场");
		$tition_cate_id = RecoveryProductCategory::getCategoryIdByName("办公闲置");
		//$product = RecoveryProduct::getProductByCateAndUid([$free_cate_id,$tition_cate_id,$param["category_id"]], $param["user_id"]);
		$product = RecoveryProduct::getProductByUid($param["user_id"]);

		if(!empty($param["user_dx"])) {
			foreach ($product as $key => &$val) {
				$yx = explode(',', $param["user_dx"]);
				$val['distance'] = self::get_distance(explode(",", $val["dx"]), $yx);
			}
		}
		$user_find["product"] = $product;


		return $user_find;
	}



	/**
	 * 个人商家主页标签
	 * @param $user_id
	 * @return string[]
	 * @throws \think\db\exception\DataNotFoundException
	 * @throws \think\db\exception\ModelNotFoundException
	 * @throws \think\exception\DbException
	 */
	public static function getUserShopTag($user_id = '')
	{
		$user_day = self::getUserDay($user_id);
		return [
			"卖家已实名",
			"当面验货",
			"随时交易",
			"入驻".$user_day."天",
			"买家自提",
		];
	}


	/**
	 * 获取用户入驻天数
	 * @param $user_id
	 * @return float
	 * @throws \think\db\exception\DataNotFoundException
	 * @throws \think\db\exception\ModelNotFoundException
	 * @throws \think\exception\DbException
	 */
	public static function getUserDay($user_id = '')
	{
		$user_product_time = RecoveryProduct::where("uid", $user_id)->order("id","asc")->limit(1)->find();
		if(empty($user_product_time["create_time"])) return 1;

		$user_time = $user_product_time["create_time"];
		$expire_time = ceil((time() - $user_time) / (3600*24));
		return $expire_time;
	}



	/**
	 * 闲置-模糊搜索
	 * @param $params
	 * @return array
	 * @throws \think\db\exception\DataNotFoundException
	 * @throws \think\db\exception\DbException
	 * @throws \think\db\exception\ModelNotFoundException
	 */
	public static function getListLikeData($params = [])
	{
		if($params["type"] == 1){
			if(empty($params["keyword"])) return [];
			$list["keyword"] = $params["keyword"];
			$list["list"] = self::whereNull("delete_time")->where("type", 1)->where("product_name","like",'%'.$params["keyword"].'%')->field("id,product_name")->select()->toArray();
			return $list;
		}

		if($params["type"] == 2){
			if(empty($params["keyword"])) return [];
			$list["keyword"] = $params["keyword"];
			$job_seeker = RecruitJobSeeker::whereNull("delete_time")->where("user_name","like",'%'.$params["keyword"].'%')->field("id,user_name")->select()->toArray();
			//$job_company = RecruitCompany::whereNull("delete_at")->where("name","like",'%'.$params["keyword"].'%')->field("id,name")->select()->toArray();
			$list["list"] = $job_seeker; //array_merge($job_seeker, $job_company);
			return $list;
		}
		return [];
	}



	/**
	 * 宝贝管理列表 - 启用禁用
	 * @param $param
	 * @return string
	 */
	public static function enableRecoveryProductStatus($param = [])
	{
		$status = self::where("id", $param['id'])->value("on_sale");
		$msg = '';
		if($status == 1){   //1上架 2下架
			$enable = 2;
			$msg = "下架成功";
		}else{
			$enable = 1;
			$msg = "上架成功";
		}
		self::where("id", $param['id'])->update(['on_sale' => $enable]);
		return $msg;
	}



    public static function getProductLikeData($params = [])
    {
        if(empty($params["keyword"])) return [];

        $water_cate_ids = StoreProductCategory::getChildCategory('百街水站');

        $list["keyword"] = $params["keyword"];
        $list["list"] = StoreProduct::where(["is_show"=>1, "is_verify"=>1, "is_del"=>0])
            ->where("store_name","like",'%'.$params["keyword"].'%')
            ->where(function ($query) use ($water_cate_ids){
                $water_category_ids = implode(",", $water_cate_ids);
                $query->whereNotIn('cate_id', $water_cate_ids);
                $query->where('cate_id', 'NOT LIKE', "'{$water_category_ids}'");
                $query->where('store_name', 'NOT LIKE', "%水票%");
                $query->where('store_name', 'NOT LIKE', "%送水%");
            })
            ->field("id,store_name")
            ->select()->toArray();
        return $list;
    }



    public static function syncCreateUser($user = [])
    {
        $user_find = Db::connect('mysql2')->table('eb_user')->where("phone", $user["phone"])->find();
        if(empty($user_find)){
            return Db::connect('mysql2')->table('eb_user')->insert($user);
        }
    }



    public static function syncUserBill($userBill = [])
    {
        return Db::connect('mysql2')->table('eb_user_bill')->insert($userBill);
    }


    public static function updateUserInfo($user = [])
    {
        if(!empty($user["phone"])){
            Db::connect('mysql2')->table('eb_user')->where("phone", $user["phone"])->update($user);
        }
    }


    public static function updateUserNowMoney($phone = '', $inc_now_money = 0)
    {
        if(!empty($inc_now_money) && !empty($phone)){
            Db::connect('mysql2')->table('eb_user')->where('phone', $phone)->inc('now_money', $inc_now_money)->update();
        }
    }


}